import { Popup, Toast } from "antd-mobile";
import Header from "@/components/header";
import { useState, useEffect, useMemo } from "react";
import { ceil } from "lodash";
import { usePaymentCodes } from "@/hooks/usePaymentCodes";
import { useGlobalTimer } from "@/utils/simpleTimer";
import PayCode from "@/components/payCode";
import PayDiscount from "@/components/payDiscount";
import { BackgroundButton } from "../../components/button";
import Card, { CardItem } from "@/components/Card";
import aidouImg from "@/assets/images/aidou.png";
import goImg from "@/assets/images/go.png";
import addImg from "@/assets/images/address.png";

import aidoubackground from "@/assets/images/aidoubackground.jpg";
import priBtn from "@/assets/images/priBtn.png";
import { PAYCODE_CONFIG_LIST } from "@/utils/const";
import "./index.less";
import { LOCAL_APP_INFO } from "../../utils/const";
import { useNavigate } from "react-router-dom";
import qrCodeIcon from "@/assets/images/bar_code.png";
import orderIcon from "@/assets/images/bot_order.png";
import Footer from "../../components/footer";
import CustomModal from "../../components/customModal";
import ActiveModal from "../../components/active";
import { useLocalStorageState, useWebSocket } from "ahooks";
import { getQrCode, memberPay, getPoint } from "@/api/paycode";
import { GeoWatcher } from "@/utils";

const mathRandom = Math.random();

function PayCodePage() {
  const [beans] = useState(0);
  const [appInfoData] = useLocalStorageState(LOCAL_APP_INFO);
  const [submitLocalData, setSubmitLocalData] =
    useLocalStorageState("SUBMIT_LOCAL_DATA");
  const [realDeduct, setRealDeduct] = useLocalStorageState("DEDUCT_COUNT");
  const [visibleDeduct, setVisibleDeduct] = useState(false);
  const [deductData, setDeductData] = useState({});
  const [isError, setIsError] = useState(false);
  console.log(realDeduct, "realDeduct");

  const { connect, latestMessage, disconnect, readyState, sendMessage } =
    useWebSocket(
      `wss://jx-yxdj.chinaums.com/bykj/wss/websocket/${appInfoData?.phone}_${mathRandom}`,
      {
        reconnectInterval: 1000,
        reconnectLimit: 100,
      }
    );

  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [codeValue, setCodeValue] = useState();
  const { qrCodeUrl, barcodeRef, isGenerating, error, refreshCodes } =
    usePaymentCodes(codeValue);
  const { time, refresh, stop, destroy, isRunning } = useGlobalTimer();

  const handleViewBill = () => {
    navigate("/orders");
  };

  const handleGoToMerchants = () => {
    console.log("前往商户");
  };

  const onGetQrCode = () => {
    getQrCode()
      .then((res) => {
        setCodeValue(res?.data?.qrNo);
      })
      .then(() => {
        refresh();
        refreshCodes(); // 刷新支付码
      })
      .catch(() => {
        stop();
        destroy();
      });
  };

  // 检查豆子
  const onGetPoint = () => {
    getPoint().then((res) => {
      const showPoint = res.data?.showPoint;
      setDeductData(res.data);
      if (showPoint == "1") {
        setVisibleDeduct(true); // 豆的开关
      } else {
        onGetQrCode();
      }
    });
  };

  useEffect(() => {
    connect();
    onGetPoint();
    // 组件卸载时清理资源
    return () => {
      disconnect();
      destroy();
      stop()
    };
  }, []);

  useEffect(() => {
    // 只有在连接状态且收到新消息时才处理
    const messageData = JSON.parse(latestMessage?.data || "{}");
    if (readyState === 1 && messageData.isOpen) {
      // 是否打开
      setSubmitLocalData(messageData);
      setVisible(true);
    } else {
      // 判断和包知否支付成功后直接跳
      if (messageData?.isSuccess) {
        Toast.show({
          icon: "success",
          content: "订单支付成功 即将跳转到成功页",
          duration: 2000,
        });
        setTimeout(() => {
          Toast.clear();
          setVisible(false);
          disconnect();
          destroy();
          navigate("/success?orderId=" + messageData?.orderId);
        }, 2000);
      } else if (messageData?.isError) {
        // 如何关闭
        setIsError(true);
      } else {
        setVisible(messageData.isOpen || Number(realDeduct || 0));
      }
    }
  }, [readyState, latestMessage?.data]);

  useEffect(() => {
    // 没有运行则关闭弹框
    if (!isRunning) {
      if (readyState === 1) {
        sendMessage("close");
      }
    }
  }, [isRunning]);

  console.log(latestMessage?.data, "latestMessage.data");

  return (
    <div className="paycode-page">
      <Header title={visible ? "收银台" : "亮码付"} />
      <div className="paycode-content">
        <MemberComponent iphone={appInfoData?.phone} />
        <PayCode
          barcodeRef={barcodeRef}
          codeValue={codeValue}
          qrCodeUrl={qrCodeUrl}
          countdown={time}
          isGenerating={isGenerating}
          error={error}
          onRefresh={onGetQrCode}
          isRunning={isRunning}
        />

        {!visible && (
          <PaycodeCardContainer
            beans={beans}
            savings={deductData?.saveMoney || 0}
            handleViewBill={handleViewBill}
          />
        )}

        <BeanBanner handleGoToMerchants={handleGoToMerchants} />

        <PayPopup
          visible={visible}
          data={submitLocalData}
          deductData={deductData}
          realDeduct={realDeduct}
          handleCancel={() => {
            sendMessage("close");
            setRealDeduct(0);
          }}
        />
      </div>
      <Footer>
        <div className="bottom-nav">
          <div className="nav-item active">
            <div className="nav-icon">
              <img src={qrCodeIcon} width={40} height={40} alt="" />
            </div>
            <span>亮码付</span>
          </div>
          <div className="nav-item">
            <div
              className="nav-icon"
              onClick={() => {
                navigate("/orders");
              }}
            >
              <img src={orderIcon} width={40} height={40} alt="省钱账单" />
            </div>
            <span>省钱账单</span>
          </div>
        </div>
        /
      </Footer>
      {/* 活动弹框 */}
      <ActiveModal
        visible={visibleDeduct}
        onClose={() => {
          setVisibleDeduct(false);
          onGetQrCode();
        }}
        onConfirm={async () => {
          setVisibleDeduct(false);
          onGetQrCode();
        }}
        title="注意：仅2025年9月26-10月10日展会期间可领取"
      />
      <CustomModal
        visible={isError}
        mode="confirm"
        title="非指定商户无法支付!"
        message="请前往“附近商户”查看"
        onConfirm={() => {
          sendMessage("close");
          setIsError(false);
          navigate("/nearby");
        }}
        onCancel={() => {
          sendMessage("close");
          setIsError(false);
        }}
      />
    </div>
  );
}

const MemberComponent = ({ iphone }) => {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);

  const handleConfirm = async () => {
    setVisible(false);
    navigate("/nearby");
  };

  const checkLocationPermission = async () => {
    const checkResult = await GeoWatcher.check();
    if (!checkResult || checkResult.permission === "denied") {
      setVisible(false);
    } else {
      setVisible(true);
    }
  };

  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <div className="member-card">
      <div className="member-header">
        <div className="member-info">
          <div className="member-info-left-top">
            <div className="member-icon" />
            <span className="member-text">亮码付会员</span>
          </div>
          <div className="greeting">下午好，尊敬的{iphone}</div>
        </div>
        <div
          className="nearby-merchants"
          onClick={() => checkLocationPermission()}
        >
          <img src={addImg} alt="" width={18} height={18} />
          <span className="nearby-merchants-text">附近商户</span>
          {/* <img src={startSvg} alt="" width={14} height={14} /> */}
          <span>{">"}</span>
        </div>
      </div>
      <div className="promo-banner">更多优惠折扣即将开启，敬请期待！</div>

      <CustomModal
        visible={visible}
        mode={"position"}
        position={"center"}
        onConfirm={async () => {
          handleConfirm();
        }}
        onCancel={handleCancel}
      />
    </div>
  );
};

const PaycodeCardContainer = ({ beans, handleViewBill, savings }) => {
  const navigate = useNavigate();
  return (
    <div className="paycode-card-container">
      {/* <div className="discount-tags">
        <div className="discount-tag">亮码付会员折扣:95折</div>
        <div className="divider"></div>
        <div></div>
        <div className="balance-tag">当前数智豆余额: {beans}</div>
      </div> */}
      {/* 省钱账单区域 */}
      <div className="savings-section">
        <div className="savings-header">
          <span className="savings-title">省钱账单</span>
          <div
            className="view-bill-btn"
            onClick={() => {
              navigate("/orders");
            }}
          >
            查看账单<span className="arrow">▶</span>
          </div>
        </div>
        <div className="savings-amount">
          累计已省<span className="amount">{savings.toFixed(2)}</span>元
        </div>
        <div className="savings-tip">快来开启你的第一次省钱之旅吧~</div>
      </div>
    </div>
  );
};

const BeanBanner = ({ handleGoToMerchants }) => {
  const navigate = useNavigate();
  return (
    <div
      className="beans-banner"
      // onClick={() => {
      //   navigate("/deduct?value=" + deductData.value || 200);
      // }}
    >
      <img src={aidouImg} alt="数智豆" className="beans-icon" />
      <div className="beans-content">
        <img src={aidoubackground} alt="" width={140} height={30} />
        <div className="beans-subtitle">你身边的折扣优惠商户</div>
        <div className="beans-title">数智豆抵扣商户</div>
        <div className="beans-desc">数智豆可以当钱花</div>
      </div>
      <div className="go-btn" onClick={handleGoToMerchants}>
        <img src={goImg} alt="" />
      </div>
    </div>
  );
};

// 支付弹窗
const PayPopup = ({ visible, handleCancel, realDeduct, data, deductData }) => {
  const navigate = useNavigate();
  const [selectedPayment, setSelectedPayment] = useState("1");
  const [showOtherMethods, setShowOtherMethods] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalData, setModalData] = useState({});
  const [deductCount, setDeductCount] = useLocalStorageState("DEDUCT_COUNT");

  const mainMethods = PAYCODE_CONFIG_LIST.slice(0, 1);
  const otherMethods = PAYCODE_CONFIG_LIST.slice(1,2);
  const { time, destroy, isRunning } = useGlobalTimer();
  console.log(time, "time");

  const discount = useMemo(() => {
    const vlaue = ceil(Number(realDeduct) * 0.01, 4).toFixed(2);
    if (vlaue <= 0) {
      return 0;
    }
    return vlaue;
  }, [data]);

  const realValue = useMemo(() => {
    const vlaue = ceil(Number(data?.txnAmt || 0) - discount, 4).toFixed(2);
    if (vlaue <= 0) {
      return 0;
    }
    return vlaue;
  }, [data]);

  const onMemberPay = () => {
    if (realValue / Number(data?.txnAmt || 1) < 0.5) {
      Toast.show({
        content: "最大折扣为订单的50% 请重新编辑折扣",
        maskClickable: false,
        duration: 2000,
      });
      return;
    }
    memberPay({
      ...(data || {}),
      payMoney: realValue,
      pointDeductAmt: discount,
      payType: selectedPayment,
      orderAmt: data?.txnAmt,
      usePoint: deductCount || 0,
      memberDiscount: 0,
      memberDiscountAmt: 0,
    })
      .then((res) => {
        setModalData(res?.data.orderId);
        destroy();
        handleCancel();
        setDeductCount(0);

        if (selectedPayment == "2") {
          let schemeString = res?.data?.result?.replace(
            "https://www.cmpay.com/front-msa/institutionh5/single/loadingPay",
            "cmpay-netunion://nucc"
          );
          cmcc?.openOtherAPP({
            type: "0",
            packageName: "com.cmcc.hebao",
            schemeString: schemeString,
            success: function (res) {},
            error: function (res) {},
          });

          console.log(schemeString);
        } else {
          console.log(res?.data.result);
          window.location.href = res?.data.result;
        }
      })
      .catch((error) => {
        console.error("支付失败:", error);
        Toast.show({
          content: "支付失败，请重试",
          maskClickable: false,
        });
      });
  };

  const handleModalConfirm = () => {
    setModalVisible(false);
    destroy();
    handleCancel();
    setDeductCount(0);
    navigate(`/success?orderId=${modalData}`);
  };

  // 云闪付类型特殊处理
  const isSpecial = useMemo(() => {
    return false;
    return selectedPayment === "1";
  }, [selectedPayment]);

  return (
    <>
      <Popup
        visible={visible}
        onMaskClick={handleCancel}
        onClose={handleCancel}
        position="bottom"
        bodyStyle={{
          padding: "24px",
          borderTopLeftRadius: "12px",
          borderTopRightRadius: "12px",
        }}
        closeOnSwipe
        showCloseButton
        // footer={document.body}
      >
        <Card
          noCard
          hover={false}
          title={"确认订单"}
          extra={isRunning ? `剩余支付时间${time}s` : "订单失效请刷新"}
          footer={{
            discount: discount,
            realValue: realValue,
          }}
        >
          <PayDiscount
            amount={realValue}
            discount={discount}
            title={data?.shopName || "永辉超市"}
            type={""}
          />
          <div className="pay-method-divider" />
          <CardItem label="订单金额" value={data?.txnAmt} />
          {/* <CardItem label="亮码付会员折扣" value={<div>省9.5折</div>} /> */}

          {/* <CardItem
            label={isSpecial ? "使用数智豆抵扣支付" : "数值豆折扣"}
            value={
              <div
                className="discount-value"
                onClick={() => {
                  navigate(`/deduct?point=${deductData?.point || 0}`);
                }}
              >
                {realDeduct
                  ? realDeduct
                  : isSpecial
                  ? "去充值"
                  : "点击输入数值豆"}
              </div>
            }
          /> */}
          {isSpecial && (
            <div className="deduct-tip">
              数智豆抵扣后，不足部分需先充值再支付
            </div>
          )}
        </Card>

        <div className="pay-method">
          <div className="pay-method-title">
            {isSpecial ? "充值方式" : "支付方式"}
          </div>
          {mainMethods.map((method, index) => (
            <div key={method.id}>
              <div
                className="pay-method-item"
                onClick={() => setSelectedPayment(method.id)}
              >
                <img src={method.icon} alt="" className="pay-method-icon" />
                <span className="pay-method-text">{method.name}</span>
                <div
                  className={`pay-method-radio ${
                    selectedPayment === method.id ? "selected" : ""
                  }`}
                >
                  {selectedPayment === method.id && "✓"}
                </div>
              </div>
              {<div className="pay-method-divider"></div>}
            </div>
          ))}

          <div
            className="other-payment-methods"
            onClick={() => setShowOtherMethods(!showOtherMethods)}
          >
            <span>其他支付方式</span>
            <span className={`arrow ${showOtherMethods ? "up" : "down"}`}>
              ▼
            </span>
          </div>

          {showOtherMethods &&
            otherMethods?.map((method, index) => (
              <div key={method.id}>
                <div
                  className="pay-method-item"
                  onClick={() => setSelectedPayment(method.id)}
                >
                  <img src={method.icon} alt="" className="pay-method-icon" />
                  <span className="pay-method-text">{method.name}</span>
                  <div
                    className={`pay-method-radio ${
                      selectedPayment === method.id ? "selected" : ""
                    }`}
                  >
                    {selectedPayment === method.id && "✓"}
                  </div>
                </div>
                {<div className="pay-method-divider"></div>}
              </div>
            ))}
        </div>

        <BackgroundButton
          type="primary"
          backgroundImage={priBtn}
          className="pay-btn"
          block
          onClick={() => {
            if (!isRunning) {
              Toast.show({
                content: "订单失效请刷新",
                maskClickable: false,
              });
              return;
            }
            Toast.show({
              content: "正在支付...",
              icon: "loading",
              maskClickable: false,
            });
            
            onMemberPay();
          }}
        >
          {isSpecial ? "立即充值并支付" : "立即支付"}
        </BackgroundButton>
      </Popup>
      <CustomModal
        mode="success"
        visible={modalVisible}
        title="支付成功"
        message=" "
        onConfirm={handleModalConfirm}
      />
    </>
  );
};

export default PayCodePage;
